const jsZip = require('jszip')
const { Compilation } = require('webpack')
// webpack5
module.exports = class SourceMapHandleV5 {
  constructor({customHandlerAdapter}) {
    this.customHandlerAdapter = customHandlerAdapter
  }

  apply(compiler) {
    let zip
    compiler.hooks.thisCompilation.tap('sourceMapHandle', (compilation) => {
      zip = new jsZip()
      compilation.hooks.processAssets.tap({
        name: 'sourceMapHandle',
        stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
      }, (assets) => {
        Object.keys(assets).forEach(fileName => {
          const asset = assets[fileName]
          if (fileName.endsWith('.js.map')) {
            zip.file(fileName, asset.source())
            compilation.deleteAsset(fileName)
          }
        })
      })
    })
    compiler.hooks.done.tapAsync('sourceMapHandle', (_, cb) => {
      zip.generateAsync({ type: 'nodebuffer' }).then(content => {
        this.customHandlerAdapter.handle(content).finally(cb)
      })
    })
  }
}